package com.johnny.util;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import com.johnny.data.Game28MathInfo;
import com.johnny.data.Game28MathResult;

public class Casino28GameMath {
	private static Casino28GameMath instance = new Casino28GameMath();
	private Random random = new Random(System.currentTimeMillis());

	public static Casino28GameMath getInstance() {
		return instance;
	}

	public List<Integer> shuffle() {
		List<Integer> result = new ArrayList<>();
		for (int i = 0; i < 40; i++) {
			int card = random.nextInt(10);
			int count = 0;
			for (Integer integer : result) {
				if (integer == card)
					count++;
			}
			if (count == 4) {
				i--;
				continue;
			} else {
				result.add(card);
			}
		}
		return result;
	}

	public void calculate(Game28MathInfo mathInfo) {

		Game28MathResult result = mathod(mathInfo.getBankerCards(), mathInfo.getDoor1Cards());
		mathInfo.setDoor1Result(result);

		result = mathod(mathInfo.getBankerCards(), mathInfo.getDoor2Cards());
		mathInfo.setDoor2Result(result);

		result = mathod(mathInfo.getBankerCards(), mathInfo.getDoor3Cards());
		mathInfo.setDoor3Result(result);

	}

	private Game28MathResult mathod(int[] bankerCards, int[] door1Cards) {

		int bankerFraction = calculateFraction(bankerCards);
		int doorFraction = calculateFraction(door1Cards);
		if (bankerFraction > doorFraction)
			return Game28MathResult.loss;
		else if (bankerFraction < doorFraction)
			return Game28MathResult.win;
		else
			return Game28MathResult.draw;
	}

	private int calculateFraction(int[] cards) {
		if (cards[0] == 0 && cards[1] == 0)
			return 100000;
		else if ((cards[0] == 2 && cards[1] == 8) || (cards[0] == 8 && cards[1] == 2)) {
			return 99000;
		} else if (cards[0] == cards[1]) {
			return cards[0] * 1000;
		} else {
			int fraction = cards[0] + cards[1];
			if (fraction >= 10) {
				fraction -= 10;
			}
			fraction = fraction * 100;
			if (cards[0] > cards[1])
				fraction = fraction + cards[0] * 10 + cards[1];
			else
				fraction = fraction + cards[1] * 10 + cards[0];
			return fraction;
		}
	}
}
